package org.codingq92.frame.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * KafkaConsumerTest
 *
 * @author CodingQ92
 */
public class KafkaConsumerTest {
    public static void main(String[] args) {
        HashMap<String, Object> configMap = new HashMap<>();
        // kafka服务器地址
        configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        // 序列化操作
        configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // 配置消费组
        configMap.put(ConsumerConfig.GROUP_ID_CONFIG, "CodingQ92");
        try (KafkaConsumer<String, Object> consumer = new KafkaConsumer<>(configMap)) {
//            listTopics(consumer);
            // 订阅主题
            consumer.subscribe(List.of("first"));
            // 拉取数据
            while (true) {
                ConsumerRecords<String, Object> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, Object> record : records) {
                    System.out.println("收到消息>>>" + record);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static void listTopics(KafkaConsumer<String, Object> consumer) {
        Map<String, List<PartitionInfo>> listMap = consumer.listTopics();
        System.out.println(">>>>>>>>>>>>>>获取Topic>>>>>>>>>>>>>>>>>");
        for (Map.Entry<String, List<PartitionInfo>> entry : listMap.entrySet()) {
            for (PartitionInfo partitionInfo : entry.getValue()) {
                System.out.println("TopicName: " + entry.getKey() + ", 分区：" + partitionInfo.toString());
            }
        }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }
}
